package com.sphd.restaurantsystem.activitys.manager;

import android.Manifest;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.content.CursorLoader;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.restaurantsystem.R;
import com.sphd.restaurantsystem.base.BaseActivity;
import com.sphd.restaurantsystem.base.RestaurantUrl;
import com.sphd.restaurantsystem.info.ManagerInfo;
import com.sphd.restaurantsystem.presenter.AddManagerPresenterImpl;
import com.sphd.restaurantsystem.utils.Constant;
import com.sphd.restaurantsystem.view.AddManagerView;
import com.wzh.frame.utils.MyUtils;
import com.wzh.frame.utils.StringUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class AddManagerActivity extends BaseActivity implements AddManagerView {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.dianming)
    MaterialEditText dianming;
    @BindView(R.id.dianzhang_name)
    MaterialEditText dianzhangName;
    @BindView(R.id.dianzhang_phone)
    MaterialEditText dianzhangPhone;
    @BindView(R.id.phone_address)
    ImageView phoneAddress;
    @BindView(R.id.update_btn)
    Button updateBtn;
    Bundle bundle;
    Intent intent;
    ManagerInfo managerInfo;
    private AddManagerPresenterImpl addManagerPresenter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_manager);
        ButterKnife.bind(this);
        addActivity(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> finish());
    }

    private void initView() {
        setTitleBar(toolbar, "店长管理");
        addManagerPresenter = new AddManagerPresenterImpl(this);
        intent = getIntent();
        bundle = intent.getExtras();
        managerInfo = (ManagerInfo) bundle.getSerializable(Constant.MANAGERINFO);
        dianming.setText(!TextUtils.isEmpty(managerInfo.getCg_name()) ? managerInfo.getCg_name() : "待编辑");
        dianzhangName.setText(!TextUtils.isEmpty(managerInfo.getStaff_name()) ? managerInfo.getStaff_name() : "待编辑");
        dianzhangPhone.setText(!TextUtils.isEmpty(managerInfo.getStaff_phone()) ? managerInfo.getStaff_phone() : "待编辑");
    }

    @OnClick({R.id.phone_address, R.id.update_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.phone_address:
                AddManagerActivityPermissionsDispatcher.onSuccesWithCheck(this);
                break;
            case R.id.update_btn:
                // TODO: 2016/11/8  明日的起点
                if (TextUtils.isEmpty(dianzhangName.getText().toString().trim())) {
                    dianzhangName.setError("姓名不能为空");
                } else {
                    if (TextUtils.isEmpty(dianzhangPhone.getText().toString().trim())) {
                        dianzhangPhone.setError("手机号码不能为空");
                    } else {
                        if (!MyUtils.isMobileNO(dianzhangPhone.getText().toString().trim())) {
                            dianzhangPhone.setError("请输入正确的手机号码");
                        } else {
                            addData();
                        }
                    }
                }
                break;
        }
    }

    private void addData() {
        addManagerPresenter.addData(RestaurantUrl.Httptitle
                + RestaurantUrl.AddDianZhang + "cgid=" +
                managerInfo.getStaff_cgid() + "&name=" + StringUtils.utf8Encode(dianzhangName.getText().toString().trim()) +
                "&phone=" + dianzhangPhone.getText().toString().trim());
    }

    @NeedsPermission(Manifest.permission.READ_CONTACTS)
    void onSucces() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setData(ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(intent, 1);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AddManagerActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale(Manifest.permission.READ_CONTACTS)
    void onCause(final PermissionRequest request) {
    }

    @OnPermissionDenied(Manifest.permission.READ_CONTACTS)
    void onBreak() {
        toast("未得到许可权限将不能从电话本获取电话");
    }

    @OnNeverAskAgain(Manifest.permission.READ_CONTACTS)
    void onNever() {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            Uri contactData = data.getData();
            CursorLoader cursorLoader = new CursorLoader(this, contactData,
                    null, null, null, null);
            // 查询联系人信息
            Cursor cursor = cursorLoader.loadInBackground();
            // 如果查询到指定的联系人
            if (cursor.moveToFirst()) {
                String contactId = cursor.getString(cursor
                        .getColumnIndex(ContactsContract.Contacts._ID));
                // 获取指定的联系人查询该联系人的信息
                String name = cursor
                        .getString(cursor
                                .getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
                String phoneNumbere = "此联系人暂时未输入电话号码";
                Cursor phones = getContentResolver().query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                + "=" + contactId, null, null);
                if (phones.moveToFirst()) {
                    // 取出电话号码
                    phoneNumbere = phones
                            .getString(phones
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                }
                //关闭游标
                phones.close();
                //显示联系人与联系电话
                dianzhangName.setText(!TextUtils.isEmpty(name) ? name : !TextUtils.isEmpty(managerInfo.getStaff_name()) ? managerInfo.getStaff_name() : "待编辑");
                dianzhangPhone.setText(phoneNumbere);

            }
        }
    }

    @Override
    public void recres(int res) {
        if (res == 0) {
            toast("设置失败");
        } else if (res == 1) {
            toast("设置成功");
            setResult(1);
            finishActivity(this);
        } else if (res == 2) {
            toast("已存在");
        }
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();
    }
}
